package it.unibz.ti2.internetPizzeria.dao;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;

import it.unibz.ti2.internetPizzeria.entities.User;

/**
 * Authenticating user and creating user accounts
 */
public class UserDAO extends BaseDAO{

	/**
	 * Saves user in database
	 * @param user object to be saved
	 * @throws DuplicatedLoginException
	 */
	public void addNewUser(User user) throws DuplicatedLoginException{
		
		if (this.equalPropertyExists("login", user.getLogin())){
			throw new DuplicatedLoginException();
		}
		super.saveObject(user);
		
	}

	/**
	 * Retreives user object that has specified login from database 
	 * @param login user's login
	 * @return user object that has specified login
	 */
	public User getUserByLogin(String login) {
		Criteria criteria = session.createCriteria(User.class);				
		criteria.add(Expression.eq("login", login));				
		User result = (User) criteria.uniqueResult();
		return result;
	}
	
	/**
	 * Retreives user object that has specified id from database 
	 * @param id user's id
	 * @return user object that has specified id
	 */
	public User getUser(long id){
		Criteria criteria = session.createCriteria(User.class);				
		criteria.add(Expression.idEq(id));
		User result = (User) criteria.uniqueResult();
		return result;
	}

	private boolean equalPropertyExists(String property, String value) {
		Criteria criteria = session.createCriteria(User.class);

		criteria.add(Expression.eq(property, value));

		User result = (User) criteria.uniqueResult();
		return (result != null);
	}
}
